package com.basics.common.utils.video;

import com.basics.common.utils.DateUtils;
import com.basics.common.utils.IdUtils;
import com.basics.common.utils.oss.AliOSSUtil;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;

/**
 * @author summer
 * @date 2021-11-02  15:02
 */
public class VideoUtils {
    /**
     * 获取指定视频的帧并保存为图片
     * @throws Exception
     */
    public static CoverVo fetchPic(InputStream is,String imgSuffix,String key) throws Exception{
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(is);
        ff.start();
        int lenght = ff.getLengthInFrames();
        String rotate_old=ff.getVideoMetadata("rotate");//视频旋转角度，可能是null
        String url = "";
        int i = 0;
        Frame frame = null;
        while (i < lenght) {
            // 过滤前5帧，避免出现全黑的图片，依自己情况而定

            frame = ff.grabFrame();

            if ((i > 5) && (frame.image != null)) {
                break;
            }
            i++;
        }

        CoverVo vo = new CoverVo();
        Java2DFrameConverter converter =new Java2DFrameConverter();
        BufferedImage srcBi =converter.getBufferedImage(frame);
        int owidth = srcBi.getWidth();
        int oheight = srcBi.getHeight();
        // 对截取的帧进行等比例缩放
//        int width = 800;
//        int height = (int) (((double) width / owidth) * oheight);
//        BufferedImage bi = new BufferedImage(owidth, oheight, BufferedImage.TYPE_3BYTE_BGR);
//        bi.getGraphics().drawImage(srcBi.getScaledInstance(owidth, oheight, Image.SCALE_SMOOTH),0, 0, null);
//        if(rotate_old!=null && !rotate_old.isEmpty()){
//            int rotate=Integer.parseInt(rotate_old);
//            bi = rotatePhonePhoto(bi,rotate);
//        }
        vo.setWidth(owidth);
        vo.setHeight(oheight);
        InputStream inputStream = null;
        try {

            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(srcBi, imgSuffix, os);
            inputStream = new ByteArrayInputStream(os.toByteArray());
            url = AliOSSUtil.uploadInputSteam("videoCoverImg/"+ key+"." +imgSuffix, inputStream);
            vo.setCoverImg("https://"+url);
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(inputStream!=null){
                inputStream.close();
            }
        }
        ff.stop();
        return vo;
    }

    /**
     * 旋转照片
     *
     * @return
     */
    public static BufferedImage rotatePhonePhoto(BufferedImage src, int angel) {
        try {
            int src_width = src.getWidth(null);
            int src_height = src.getHeight(null);

            int swidth = src_width;
            int sheight = src_height;

            if (angel == 90 || angel == 270) {
                swidth = src_height;
                sheight = src_width;
            }
            Rectangle rect_des = new Rectangle(new Dimension(swidth, sheight));
            BufferedImage res = new BufferedImage(rect_des.width, rect_des.height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = res.createGraphics();
            g2.translate((rect_des.width - src_width) / 2, (rect_des.height - src_height) / 2);
            g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);
            g2.drawImage(src, null, null);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 将MultipartFile转换为File
     * @param multiFile
     * @return
     */
    public static File MultipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();

        // 若须要防止生成的临时文件重复,能够在文件名后添加随机码

        try {
            File file = File.createTempFile(fileName, ".mp4");
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
